package me.huha.service.api.impl;

import java.util.HashMap;
import java.util.Map;

import me.huha.entity.IpMessageEntity;
import me.huha.service.api.IpCityApiService;
import me.huha.util.HttpClientUtils;
import me.huha.util.IpUtils;
import me.huha.util.JsonUtils;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

/**
 * 类名: SinaIpApiUtils.java 
 * 描述: TODO 
 * 作者: Yepx 
 * 创建日期: 2017年2月9日 上午9:16:44
 */
public class SinaIpCityImpl implements IpCityApiService {
    
	private static Logger logger = Logger.getLogger(SinaIpCityImpl.class);
	/**
	 * 新浪接口URL
	 */
	private final static String TAOBAO_URL = "http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json";

	/**
	 * 根据IP和类型查找地区信息
	 * 
	 * @param ip
	 * @param apiType
	 * @return
	 */
	public IpMessageEntity getAddresses(String ip) {
		
		IpMessageEntity ipMessage = new IpMessageEntity();
		Map<String, String> paramsMap = new HashMap<String, String>();
		paramsMap.put("ip", ip);
		String retstring = HttpClientUtils.post(TAOBAO_URL, paramsMap);
		if (StringUtils.isEmpty(retstring) || "null".equals(retstring)) {
			return null;
		}
		try{
			Map<String, Object> jsonMap = JsonUtils.parseJSON2Map(retstring);
			if (jsonMap == null || jsonMap.isEmpty()) {
				return null;
			}
			
			ipMessage.setCountry(jsonMap.get("country").toString());
			ipMessage.setRegion(jsonMap.get("province").toString());
			ipMessage.setCity(jsonMap.get("city").toString());
			ipMessage.setCounty(jsonMap.get("district").toString());
			ipMessage.setIsp(jsonMap.get("isp").toString());
			ipMessage.setIpType(IpUtils.checkIpType(ip).getName());
			ipMessage.setIp(ip);
			ipMessage.setSource(SinaIpCityImpl.class.getName());
		}catch(Exception e){
			ipMessage = null;
			logger.error(e);
			logger.error("解析出错");
		}
		return ipMessage;
	}

}
